package net.huashitong.Indicators.controller;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.sirdc.modules.core.web.JsonBaseController;
import net.huashitong.Indicators.entity.AreaCode;
import net.huashitong.Indicators.service.AreaCodeService;
import net.huashitong.until.Until;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

@Controller
@RequestMapping("/api/areaCode")
public class AreaCodeController extends JsonBaseController {
    @Override
    protected String getView(String s) {
        return null;
    }

    @Autowired
    private AreaCodeService service;
    @ResponseBody
    @RequestMapping("/saveareacode")
    public void saveAreaCode(){
        //获取地区父节点
        String areaParent = null;
        try {
            areaParent = Until.HttpGET(Until.AREA_CODE_URL_DB_URL,5000,5000);
        } catch (IOException e) {
            System.out.println(Until.AREA_CODE_URL_DB_URL);
            e.printStackTrace();
        }
        JSONObject jsonObject1 =JSONObject.parseObject(areaParent);
        if("200".equals(jsonObject1.getJSONArray("returncode"))){
            JSONArray jsonArray = jsonObject1.getJSONArray("returndata");
            List<String> acStr = new ArrayList<>();
            for(int  i =0;i<jsonArray.size();i++){
                JSONObject object  = (JSONObject)jsonArray.get(i);
                acStr.add(object.getString("code"));
            }
            for(String str : acStr){
                String areaChild = null;
                try {
                    areaChild = Until.HttpGET(Until.AREA_CODE_URL_DB_URL+"ab=appnd2"+"&p="+str,5000,5000);
                } catch (IOException e) {
                    System.out.println(Until.AREA_CODE_URL_DB_URL + "ab=appnd2" + "&p=" + str);
                    e.printStackTrace();
                }
                JSONObject jsonObject2 = JSONObject.parseObject(areaChild);
                JSONArray jsonArray2 = jsonObject2.getJSONArray("returndata");
                List<AreaCode> areaCodeList = new ArrayList<>();
                for(int  i =0;i<jsonArray2.size();i++){
                    AreaCode areaCode = new AreaCode();
                    JSONObject object  = (JSONObject)jsonArray2.get(i);
                    areaCode.setAreaCode(object.getString("code"));
                    areaCode.setAreaName(object.getString("name"));
                    areaCodeList.add(areaCode);
                }
                service.batchSave(areaCodeList);
            }
        }
    }

}
